"use client"

import type React from "react"
import { useState, useRef, useEffect } from "react"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Badge } from "@/components/ui/badge"
import { ChevronLeft, ChevronRight, ZoomIn, ZoomOut, Upload, File, RotateCw, AlertCircle } from "lucide-react"
import { cn } from "@/lib/utils"

// 模拟实时关键词数据
const mockKeywords = [
  { id: 1, text: "线性代数", timestamp: "10:15:22", confidence: 0.95 },
  { id: 2, text: "矩阵运算", timestamp: "10:16:05", confidence: 0.92 },
  { id: 3, text: "特征值", timestamp: "10:17:30", confidence: 0.88 },
  { id: 4, text: "线性变换", timestamp: "10:18:45", confidence: 0.9 },
  { id: 5, text: "向量空间", timestamp: "10:19:20", confidence: 0.85 },
  { id: 6, text: "正交基", timestamp: "10:20:15", confidence: 0.82 },
  { id: 7, text: "对角化", timestamp: "10:21:30", confidence: 0.91 },
]

export function DocumentViewer() {
  const [file, setFile] = useState<File | null>(null)
  const [pageNum, setPageNum] = useState(1)
  const [numPages, setNumPages] = useState(0)
  const [scale, setScale] = useState(1.0)
  const [isLoading, setIsLoading] = useState(false)
  const [pageImages, setPageImages] = useState<string[]>([])
  const [keywords, setKeywords] = useState(mockKeywords)
  const [activeTab, setActiveTab] = useState("upload")
  const [error, setError] = useState<string | null>(null)
  const fileInputRef = useRef<HTMLInputElement>(null)

  // 处理文件上传
  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFile = e.target.files?.[0]
    if (!selectedFile) return

    setFile(selectedFile)
    setIsLoading(true)
    setActiveTab("view")
    setError(null)

    try {
      if (selectedFile.type === "application/pdf") {
        await handlePdfFile(selectedFile)
      } else if (
        selectedFile.type === "application/vnd.openxmlformats-officedocument.presentationml.presentation" ||
        selectedFile.type === "application/vnd.ms-powerpoint"
      ) {
        await handlePptFile(selectedFile)
      } else {
        throw new Error("不支持的文件格式。请上传PDF或PPT文件。")
      }
    } catch (err) {
      console.error("Error processing file:", err)
      setError(err instanceof Error ? err.message : "处理文件时出错")
    } finally {
      setIsLoading(false)
    }
  }

  // 处理PDF文件
  const handlePdfFile = async (pdfFile: File) => {
    // 使用简单的方法模拟PDF处理
    // 在实际生产环境中，我们会使用PDF.js，但在这个环境中我们简化处理
    setNumPages(5) // 假设PDF有5页

    // 创建模拟的页面图像
    const images: string[] = []
    for (let i = 1; i <= 5; i++) {
      // 使用placeholder图像模拟PDF页面
      images.push(`/placeholder.svg?height=800&width=600&text=PDF页面${i}`)
    }

    setPageImages(images)
    setPageNum(1)

    // 模拟处理延迟
    await new Promise((resolve) => setTimeout(resolve, 1000))
  }

  // 处理PPT文件
  const handlePptFile = async (pptFile: File) => {
    // 这里是简化的实现，实际上需要使用专门的库来处理PPT
    setNumPages(3) // 假设PPT有3页

    // 创建模拟的页面图像
    const images: string[] = []
    for (let i = 1; i <= 3; i++) {
      // 使用placeholder图像模拟PPT幻灯片
      images.push(`/placeholder.svg?height=800&width=1200&text=PPT幻灯片${i}`)
    }

    setPageImages(images)
    setPageNum(1)

    // 模拟加载延迟
    await new Promise((resolve) => setTimeout(resolve, 1000))
  }

  // 翻页功能
  const goToPreviousPage = () => {
    if (pageNum > 1) {
      setPageNum(pageNum - 1)
    }
  }

  const goToNextPage = () => {
    if (pageNum < numPages) {
      setPageNum(pageNum + 1)
    }
  }

  // 缩放功能
  const zoomIn = () => {
    setScale((prevScale) => Math.min(prevScale + 0.2, 3))
  }

  const zoomOut = () => {
    setScale((prevScale) => Math.max(prevScale - 0.2, 0.5))
  }

  // 模拟每5秒更新一次关键词
  useEffect(() => {
    const interval = setInterval(() => {
      const newKeyword = {
        id: Date.now(),
        text: ["数学归纳法", "微积分", "概率论", "统计分析", "傅里叶变换"][Math.floor(Math.random() * 5)],
        timestamp: new Date().toLocaleTimeString(),
        confidence: 0.7 + Math.random() * 0.3,
      }

      setKeywords((prev) => [newKeyword, ...prev.slice(0, 6)])
    }, 5000)

    return () => clearInterval(interval)
  }, [])

  // 渲染上传文档界面
  const renderUploadContent = () => (
    <div className="flex flex-col items-center justify-center border-2 border-dashed border-gray-300 rounded-lg p-12 text-center">
      <File className="h-16 w-16 text-gray-400 mb-4" />
      <h3 className="text-lg font-semibold mb-2">上传课程文档</h3>
      <p className="text-sm text-gray-500 mb-6">支持PDF和PPT格式文件</p>
      <Input ref={fileInputRef} type="file" accept=".pdf,.ppt,.pptx" onChange={handleFileChange} className="hidden" />
      <Button onClick={() => fileInputRef.current?.click()}>
        <Upload className="mr-2 h-4 w-4" /> 选择文件
      </Button>
    </div>
  )

  // 渲染文档查看界面
  const renderViewContent = () => {
    if (isLoading) {
      return (
        <div className="flex items-center justify-center h-[500px]">
          <div className="flex flex-col items-center">
            <RotateCw className="h-8 w-8 animate-spin text-primary" />
            <p className="mt-4">正在处理文档...</p>
          </div>
        </div>
      )
    }

    if (error) {
      return (
        <div className="flex items-center justify-center h-[300px]">
          <div className="flex flex-col items-center text-center max-w-md">
            <AlertCircle className="h-12 w-12 text-red-500 mb-4" />
            <h3 className="text-lg font-semibold mb-2">处理文档时出错</h3>
            <p className="text-sm text-gray-500 mb-6">{error}</p>
            <Button
              onClick={() => {
                setActiveTab("upload")
                setError(null)
              }}
            >
              返回上传
            </Button>
          </div>
        </div>
      )
    }

    return (
      <div className="space-y-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-2">
            <Button variant="outline" size="sm" onClick={goToPreviousPage} disabled={pageNum <= 1}>
              <ChevronLeft className="h-4 w-4" />
            </Button>
            <span className="text-sm">
              第 {pageNum} 页 / 共 {numPages} 页
            </span>
            <Button variant="outline" size="sm" onClick={goToNextPage} disabled={pageNum >= numPages}>
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
          <div className="flex items-center space-x-2">
            <Button variant="outline" size="sm" onClick={zoomOut}>
              <ZoomOut className="h-4 w-4" />
            </Button>
            <span className="text-sm w-16 text-center">{Math.round(scale * 100)}%</span>
            <Button variant="outline" size="sm" onClick={zoomIn}>
              <ZoomIn className="h-4 w-4" />
            </Button>
          </div>
        </div>

        <div className="flex justify-center bg-gray-100 rounded-lg p-4 overflow-auto max-h-[500px]">
          <div
            style={{
              transform: `scale(${scale})`,
              transformOrigin: "top center",
              transition: "transform 0.2s",
            }}
          >
            {pageImages.length > 0 && pageNum <= pageImages.length ? (
              <img
                src={pageImages[pageNum - 1] || "/placeholder.svg"}
                alt={`Page ${pageNum}`}
                className="max-w-full h-auto shadow-lg"
              />
            ) : (
              <div className="bg-white p-8 rounded shadow-lg">
                <p>正在加载页面...</p>
              </div>
            )}
          </div>
        </div>

        <div className="bg-gray-50 p-4 rounded-lg">
          <div className="flex items-center justify-between mb-3">
            <h3 className="font-medium">实时课堂关键词</h3>
            <span className="text-xs text-gray-500">最近更新: {new Date().toLocaleTimeString()}</span>
          </div>
          <div className="flex flex-wrap gap-2">
            {keywords.map((keyword) => (
              <Badge
                key={keyword.id}
                variant="outline"
                className={cn(
                  "px-3 py-1 text-sm",
                  keyword.confidence > 0.9 ? "bg-green-100" : keyword.confidence > 0.8 ? "bg-blue-100" : "bg-gray-100",
                )}
              >
                {keyword.text}
                <span className="ml-2 text-xs text-gray-500">{keyword.timestamp}</span>
              </Badge>
            ))}
          </div>
        </div>
      </div>
    )
  }

  return (
    <Card className="w-full">
      <CardHeader className="pb-3">
        <div className="flex items-center justify-between">
          <CardTitle>课程文档查看器</CardTitle>
        </div>
      </CardHeader>
      <CardContent>
        <Tabs value={activeTab} onValueChange={setActiveTab}>
          <TabsList className="grid w-full grid-cols-2 mb-4">
            <TabsTrigger value="upload">上传文档</TabsTrigger>
            <TabsTrigger value="view" disabled={!file}>
              查看文档
            </TabsTrigger>
          </TabsList>
          <TabsContent value="upload">{renderUploadContent()}</TabsContent>
          <TabsContent value="view">{renderViewContent()}</TabsContent>
        </Tabs>
      </CardContent>
    </Card>
  )
}
